﻿using DG.Tweening;
using System;
using System.Diagnostics;
using System.Globalization;
using UnityEngine;
using static Enums.Timer;



public static partial class Utility
{

    /// <summary>
    /// 时间相关工具库
    /// </summary>
    public static class Timer
    {
        /// <summary>
        /// 每秒毫秒数
        /// </summary>
        public static long MsPerSecond = 1000;
        /// <summary>
        /// 每分钟毫秒数
        /// </summary>
        public static long MsPerMinute = MsPerSecond * 60;
        /// <summary>
        /// 每小时毫秒数
        /// </summary>
        public static long MsPerHour = MsPerMinute * 60;
        /// <summary>
        /// 每天毫秒数
        /// </summary>
        public static long MsPerDay = MsPerHour * 24;

        public static long SecondPerMinute = 60;
        public static long SecondPerHour = SecondPerMinute * 60;
        public static long SecondPerDay = SecondPerHour * 24;

        private static DateTime InitTime = TimeZoneInfo.ConvertTimeFromUtc(new DateTime(1970, 1, 1), TimeZoneInfo.Local);

        private static string FORMAT_D2 = "D2";

        /// <summary>
        /// 通过时间戳获取时间戳那天的凌晨时间戳
        /// </summary>
        /// <param name="timeStamp">时间戳，单位：毫秒</param>
        /// <returns></returns>
        public static long GetDayZeroTime(long timeStamp)
        {
            return timeStamp - (timeStamp + 8 * MsPerHour) % MsPerDay;
        }

        public static long GetTomorrowZeroTime(long timeStamp)
        {
            return timeStamp - (timeStamp + 8 * MsPerHour) % MsPerDay + 1 * MsPerDay;
        }

       
        /// <summary>
        /// 获取本地时间
        /// </summary>
        /// <returns></returns>
        public static long GetLocalTime()
        {
            TimeZoneInfo timeZoneInfo = TimeZoneInfo.Local;
            DateTime localDateTime = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, timeZoneInfo);
            return localDateTime.Ticks;
        }

        

        /// <summary>
        /// 计算方法耗时（Milliseconds）
        /// </summary>
        /// <param name="action">执行方法</param>
        /// <returns></returns>
        public static long ComputingElapsed(Action action)
        {
            return ComputingTime(action).ElapsedMilliseconds;
        }

        /// <summary>
        /// 计算方法耗时
        /// </summary>
        /// <param name="action">执行方法</param>
        /// <returns></returns>
        public static Stopwatch ComputingTime(Action action)
        {
            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();
            action?.Invoke();
            stopwatch.Stop();

            return stopwatch;
        }

        /// <summary>
        /// DateTime 转时间戳
        /// </summary>
        /// <param name="dateTime"></param>
        /// <returns></returns>
        public static long DateToTimeStamp(DateTime dateTime)
        {
            return (long)(dateTime - InitTime).TotalMilliseconds;
        }


        /// <summary>
        /// 字符串转 DateTime
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static DateTime StringToDateTime(string str)
        {
            var split = str.Split(new char[] { '-', ' ', ':' });
            DateTime dt = new DateTime(int.Parse(split[0]), int.Parse(split[1]), int.Parse(split[2]), int.Parse(split[3]), int.Parse(split[4]), int.Parse(split[5]));
            return dt;
        }

        /// <summary>  
        /// 时间戳Timestamp转换成日期  
        /// </summary>  
        /// <param name="time">时间 单位：秒</param>  
        /// <returns></returns>  
        public static DateTime GetDateTime(long time)
        {
            DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            long lTime = ((long)time * 10000000);
            TimeSpan toNow = new TimeSpan(lTime);
            DateTime targetDt = dtStart.Add(toNow);
            return targetDt;
        }

        /// <summary>
        /// 时间戳Timestamp转换成日期  例如：03.07
        /// </summary>
        /// <param name="timeStamp">时间戳，单位：毫秒</param>
        /// <param name="format"> 自定义格式 默认是 "MM.dd"，即：03.07</param>
        /// <returns>例如：03.07</returns>
        public static string GetMonthAndDayFormatString(long timeStamp,string format= "MM.dd")
        {
            // 将时间戳转换为 DateTime 对象
            var dt= Utility.Timer.GetDateTime(timeStamp.MsToSecond());

            // 格式化日期为指定格式（月份.日期）
            string result = dt.ToString(format);
            return result;
        }


        public static Tween Delay(float delay, Action action, bool isRealTime = false)
        {
            float timer = 0;
            var tween = DOTween.To(() => timer, value => timer = value, 1, delay).OnComplete(() => action.Invoke());
            if (isRealTime)
            {
                tween.SetUpdate(true);
            }
            return tween;
        }

        /// <summary>
        /// 毫秒转离线状态
        /// </summary>
        /// <param name="ms"></param>
        /// <param name="fmt">{0}前登录之类的</param>
        /// <returns></returns>
        public static string MsToOfflineState(long ms, string fmt)
        {
            if (ms <= 0)
                return string.Empty;

            if (ms < MsPerHour)
                return "offline_state_moment".FormatLocalize();
            else if (ms < MsPerDay)
            {
                int hour = Mathf.FloorToInt(ms / MsPerHour);
                return fmt.FormatLocalize("offline_state_hour_format".FormatLocalize(hour));
            }
            else
            {
                int day = Mathf.FloorToInt(ms / MsPerDay);
                return fmt.FormatLocalize("offline_state_day_format".FormatLocalize(day));
            }
        }

        /// <summary>
        /// 获取月-日显示
        /// </summary>
        /// <param name="timeStamp">时间戳 单位：毫秒</param>
        /// <returns></returns>
        public static string GetMonthAndDay(long timeStamp)
        {
            var date = GetDateTime(timeStamp.MsToSecond());
            return "Common_Time_MONTH_DAY".FormatLocalize(date.Month, date.Day);
        }

        /// <summary>
        /// 获取月-日-24小时
        /// </summary>
        /// <param name="timeStamp"></param>
        /// <returns></returns>
        public static string GetMonthAndDayAndHour(long timeStamp)
        {
            long basetime = 24 * 60 * 60 * 1000;
            var time = timeStamp - basetime;
            var date = GetDateTime(time.MsToSecond());
            return "Common_Time_MONTH_DAY".FormatLocalize(date.Month, date.Day) + "24:00";
        }
        /// <summary>
        /// 获取天，只取数字展示
        /// </summary>
        /// <param name="second"></param>
        /// <returns></returns>
        private static string ConverDayStrNoUnit(long second)
        {
            int days = Mathf.FloorToInt(second / SecondPerDay);
            return days.ToString(FORMAT_D2);
        }

        /// <summary>
        /// 获取格式为：2024-06-18 18:58:26 的字符串
        /// </summary>
        /// <param name="timeStamp">时间戳</param>
        /// <returns></returns>
        public static string ConverYYMMDD_HHMMSSS(long timeStamp)
        {
            // 转换为 DateTime 对象
            DateTime dateTime = GetDateTime(timeStamp.MsToSecond());

            // 转换为所需的格式字符串
            string formattedDateTime = dateTime.ToString("yyyy-MM-dd HH:mm:ss");

            return formattedDateTime;
        }
    }
}
